﻿(function () {
    var cookies = null;
    $(document).ready(function () {
        cookies = $.cookie("columnsState");
        if (cookies != undefined && cookies != {})
            cookies = JSON.parse(cookies);

        function selectRow(grid, isPrev) {
            if (grid != undefined) {
                var curRow = grid.select();
                if (!curRow.length)
                    return;
                if (curRow.collapsed)
                    curRow.collapseRow();
                var newRow;
                if (isPrev) {
                    newRow = curRow.prev();
                } else {
                    newRow = curRow.next();
                }
                if (newRow.length > 0) {
                    //var detailRow = newRow[0].className[0]; //IE9 incompatibility
                    if (newRow.hasClass("k-detail-row")) {
                        if (isPrev) {
                            newRow = newRow.prev();
                        } else {
                            newRow = newRow.next();
                        }
                    }
                    grid.select(newRow);
                    grid.expandRow(newRow);
                    $("tr.k-state-selected ~ tr.k-detail-row #tabstrip").focus();
                }
            }
        }

        //var arrowsV = [37, 39];
        $("div#grid").keydown(function (e) { // $(document.body).keydown(function (e) - chrome compatibility
            if (e.keyCode == 13 || e.keyCode == 40) {
                var grid = $("#grid").data("kendoGrid");
                selectRow(grid, false);
            }
            if (e.keyCode == 38) {
                var grid = $("#grid").data("kendoGrid");
                selectRow(grid, true);
            }
        });
    });
    var columns = [43, 60, 70, 90, 94, 68, 70, 70, 110, 110, 50, 50, 52, 48, 52, 42, 37, 70, 28];

    function getWidth(idx) {
        if (cookies != undefined && cookies != {})
            if (cookies.columns[idx].width != undefined)
                return cookies.columns[idx].width;
        return columns[idx];
    };

    var appGridDef = angular.module("gridDefined", []);

    appGridDef.controller('gridController', function ($scope, $http, $filter, Services) {
        $scope.formatDate = "dd.MM.yyyy";
        $scope.formatDateTime = "dd.MM.yyyy H:mm";
        $scope.formatsDate = ["dd/MM/yyyy", "dd.MM.yyyy", "dd-MM-yyyy", "dd MM yyyy", "dd,MM,yyyy"];
        $scope.formatsDateTime = ["dd/MM/yyyy H:mm", "dd.MM.yyyy H:mm", "dd-MM-yyyy H:mm", "dd MM yyyy H:mm", "dd,MM,yyyy H:mm",
                                 "dd/MM/yy H:mm", "dd.MM.yy H:mm", "dd-MM-yy H:mm", "dd MM yy H:mm", "dd,MM,yy H:mm",
                                 "dd/MM/yyyy Hmm", "dd.MM.yyyy Hmm", "dd-MM-yyyy Hmm", "dd MM yyyy Hmm", "dd,MM,yyyy Hmm",
                                 "dd/MM/yy Hmm", "dd.MM.yy Hmm", "dd-MM-yy Hmm", "dd MM yy Hmm", "dd,MM,yy Hmm"];
        $scope.addFormats = ["dd/MM/yy", "dd.MM.yy", "dd-MM-yy", "dd MM yy", "dd,MM,yy",
                             "dd/MM", "dd.MM", "dd-MM", "dd MM", "dd,MM", "yyyy", "dd"];
        $scope.formatsDateTime = $scope.formatsDateTime.concat($scope.formatsDate);
        $scope.formatsDate = $scope.formatsDate.concat($scope.addFormats);
        $scope.formatsDateTime = $scope.formatsDateTime.concat($scope.addFormats);

        $scope.mainGridOptions = {
            dataSource: {
                //type: "json",
                //transport: {
                //    read: serviceUri + "fixture/2/2"
                //},
                schema: {
                    model: {
                        fields: {
                            VoyageOrderDate: { type: "date" },
                            CPDate: { type: "date" },
                            LoadingOrderDate: { type: "date" },
                            DischargeOrderDate: { type: "date" },
                            BillOfLadenDate: { type: "date" },
                            LetterOfIndemnityDate: { type: "date" },
                            FreightInvoiceDate: { type: "date" },
                            CommissionInvoiceDate: { type: "date" },
                            changed: { type: "boolean" }
                        }
                    }
                },
                pageSize: 5,
                requestStart: function () {
                    $scope.loader(true);
                },
                requestEnd: function () {
                    $scope.loader(false);
                },
                sort: { field: "CPDate", dir: "desc" }
            },
            dataBound: function (e) {
                var data = $('#grid').data().kendoGrid.dataSource.view();
                for (var i = 0; i < data.length; i++) {
                    Services.commonCalc({ type: 'load', Id: data[i].Id, ports: data[i].LoadingPorts, oper: 'check' });
                    Services.commonCalc({ type: 'disch', Id: data[i].Id, ports: data[i].DischargePorts, oper: 'check' });
                }
            },
            autoBind: false,
            sortable: true,
            //navigatable: true,//IE lags
            selectable: "single",  //IE lags
            scrollable: true,
            pageable: {
                pageSizes: true,
                input: true
            },
            resizable: true,
            columnResize: onResize,
            filterable: true,
            groupable: true,
            detailTemplate: kendo.template($("#template").html()),
            detailExpand: function (e) {
                this.collapseRow(this.tbody.find(' > tr.k-master-row').not(e.masterRow));
            },
            columns: [{
                field: 'changed',
                title: "Changed",
                headerTemplate: "<div class='text-center' style='display: inline-block;'><i class='fa fa-edit fa-lg' title='Changed'></i></div>",
                template: kendo.template($("#ChangedTemplate").html()),
                width: getWidth(0)
            }, {
                field: "Type",
                title: "Type",
                groupable: false,
                width: getWidth(1)
            }, {
                field: "VesselName",
                template: kendo.template($("#VesselTemplate").html()),
                title: "Vessel",
                width: getWidth(2)
            }, {
                field: "CPDate",
                template: kendo.template($("#CPTemplate").html()),
                title: "C\\P Date",
                width: getWidth(3),
                filterable: {
                    ui: function (element) {
                        element.kendoDatePicker({
                            format: $scope.formatDate,
                            parseFormats: $scope.formatsDate
                        });
                    }
                }
            }, {
                field: "VoyageRef",
                template: kendo.template($("#VoyageTemplate").html()),
                title: "Voyage",
                width: getWidth(4)
            }, {
                template: kendo.template($("#layCanTemplate").html()),
                title: "Lay\Can",
                groupable: false,
                width: getWidth(5)
            }, {
                field: "Owner.Name",
                template: kendo.template($("#OwnerTemplate").html()),
                title: "Owner",
                width: getWidth(6)
            }, {
                field: "Charterer.Name",
                template: kendo.template($("#ChartenerTemplate").html()),
                title: "Chart.",
                width: getWidth(7)
            }, {
                template: kendo.template($("#loadPortTemplate").html()),
                title: "Loading Port",
                sortable: false,
                groupable: false,
                width: getWidth(8)
            }, {
                template: kendo.template($("#dischPortTemplate").html()),
                title: "Discharge Port",
                sortable: false,
                groupable: false,
                width: getWidth(9)
            }, {
                field: "VoyageOrderDate",
                template: kendo.template($("#VOTemplate").html()),
                title: "VO",
                width: getWidth(10),
                filterable: {
                    ui: function (element) {
                        element.kendoDateTimePicker({
                            format: $scope.formatDateTime,
                            parseFormats: $scope.formatsDateTime
                        });
                    }
                }
            }, {
                field: "LoadingOrderDate",
                template: kendo.template($("#LOTemplate").html()),
                title: "LO",
                width: getWidth(11),
                filterable: {
                    ui: function (element) {
                        element.kendoDateTimePicker({
                            format: $scope.formatDateTime,
                            parseFormats: $scope.formatsDateTime
                        });
                    }
                }
            }, {
                field: "DischargeOrderDate",
                template: kendo.template($("#DOTemplate").html()),
                title: "DO",
                width: getWidth(12),
                filterable: {
                    ui: function (element) {
                        element.kendoDateTimePicker({
                            format: $scope.formatDateTime,
                            parseFormats: $scope.formatsDateTime
                        });
                    }
                }
            }, {
                field: "BillOfLadenDate",
                template: kendo.template($("#BLTemplate").html()),
                title: "BL",
                width: getWidth(13),
                filterable: {
                    ui: function (element) {
                        element.kendoDateTimePicker({
                            format: $scope.formatDateTime,
                            parseFormats: $scope.formatsDateTime
                        });
                    }
                }
            }, {
                field: "LetterOfIndemnityDate",
                template: kendo.template($("#LoITemplate").html()),
                title: "LOI",
                width: getWidth(14),
                filterable: {
                    ui: function (element) {
                        element.kendoDateTimePicker({
                            format: $scope.formatDateTime,
                            parseFormats: $scope.formatsDateTime
                        });
                    }
                }
            }, {
                field: "FreightInvoiceDate",
                template: kendo.template($("#FITemplate").html()),
                title: "F",
                width: getWidth(15),
                filterable: {
                    ui: function (element) {
                        element.kendoDateTimePicker({
                            format: $scope.formatDateTime,
                            parseFormats: $scope.formatsDateTime
                        });
                    }
                }
            }, {
                field: 'CommissionInvoiceDate',
                template: kendo.template($("#CityTemplate").html()),
                title: "C",
                width: getWidth(16),
                filterable: true
            }, {
                field: "DemurrageStatus.value",
                template: kendo.template($("#demurrageTemplate").html()),
                title: "D",
                width: getWidth(17),
                groupable: false,
                filterable: {
                    ui: demurrageFilter
                }
            }, {
                template: kendo.template($("#CloseTemplate").html()),
                title: 'Close',
                groupable: false,
                headerTemplate: "<div class='text-center' style='display: inline-block;'><i class='fa fa-times fa-lg' title='Close'></i></div>",
                width: getWidth(18)
            }]//, dataBound: addExtraStylingToGrid
        };

        function demurrageFilter(element) {
            element.kendoDropDownList({
                dataSource: ['Not Exist', 'Unknown', 'Reminder Sent', 'Claim Received', 'Claim Forwarded',
                        'Claim Acknowledged', 'Accepted', 'No', 'Invoiced'],
                optionLabel: "--Select Value--"
            });
        };

        $scope.coBrokersGrid = function (dataItem) {
            return {
                dataSource: {
                    data: dataItem,
                    serverPaging: false,
                    serverSorting: true,
                    serverFiltering: true,
                    pageSize: 5,
                },
                scrollable: true,
                sortable: true,
                resizable: true,
                pageable: true,
                columns: [
                    { field: "CollectCommission", template: kendo.template($("#ComissionTemplate").html()), title: "Collect", width: "20px" },
                    { template: kendo.template($("#brokeForTemplate").html()), title: "BrokeFor", width: "25px" },
                    { field: "Name", template: '<a href="#=CrmUrl#" tabindex="-1" target="_blank">#=Name#</a>', title: "Name", width: "60px" },

                    { field: "CommissionPercentage", template: '#=CommissionPercentage*100#%', title: "Comm.", width: "35px" },
                    { field: "OperatorName", title: "Operator", width: "65px" }
                ]
            };
        };
    });
})()